<template>
  <div class="app-container">
    <el-form ref="elForm" :disabled="$route.query.isInfo" :model="formData" :rules="rules" size="medium"
      label-width="150px">
      <h2 style="text-align: center">证书</h2>
      <el-tabs v-model="formData.type" @tab-click="changeTab">
        <el-tab-pane label="公路/水运" name="1"></el-tab-pane>
        <el-tab-pane label="建设工程" name="2"></el-tab-pane>
        <!-- <el-tab-pane label="建设审核" name="3"></el-tab-pane> -->
      </el-tabs>
      <el-row>
        <el-col :span="24">
          <!-- <el-form-item label="资格证书" prop="certTypeId"> -->
          <!-- <treeselect
              @input="change"
              value-consists-of="LEAF_PRIORITY"
              multiple
              v-model="formData.certTypeId"
              :options="cretList"
              :normalizer="normalizer"
              placeholder="选择资格证书"
          />-->
          <!-- <el-form-item label="资格证书" >
            <el-checkbox-group v-model="formData.certTypeId" @change="change">
              <el-checkbox
                :label="item.certTypeId"
                :value="item.certTypeId"
                v-for="item in cretListOld"
                >{{ item.certTypeName }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>-->
          <!-- </el-form-item> -->
          <el-table
            v-loading="loading"
            border
            :data="deptList"
            row-key="certTypeId"
            :default-expand-all="isExpandAll"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column
              prop="list"
              width="55"
              type="selection"
              @selection-change="change"
              :selectable="(row) => !row.disabled"
              v-if="formData.type == 1"
            >
              <!-- v-if="scope.row.ancestors&&scope.row.ancestors.split(',').length==4" -->
              <template
                slot-scope="scope"
                v-if="
                  scope.row.ancestors &&
                  scope.row.ancestors.split(',').length == 4
                "
              >
                <el-checkbox
                  v-model="scope.row.selected"
                  @change="onRowSelect(scope.row, scope.$index)"
                ></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column
              prop="list"
              width="55"
              type="selection"
              @selection-change="change"
              :selectable="(row) => !row.disabled"
              v-if="formData.type == 2"
            >
              <template
                slot-scope="scope"
                v-if="
                  scope.row.ancestors &&
                  (scope.row.ancestors.split(',').includes('4')
                    ? scope.row.ancestors.split(',').length == 6
                    : scope.row.ancestors.split(',').length == 4)
                "
              >
                <el-checkbox
                  v-model="scope.row.selected"
                  @change="onRowSelect(scope.row, scope.$index)"
                ></el-checkbox>
              </template>
            </el-table-column>
            <!-- <div v-if="formData.type == 2 && (scope.row.ancestors.split(',')).includes('420')">
              <el-table-column prop="list" width="55" type="selection" @selection-change="change"
                :selectable="row => !row.disabled"  v-if="scope.row.ancestors && scope.row.ancestors.split(',').length == 6">
                <template slot-scope="scope">
                  {{ (scope.row.ancestors.split(',')).includes('4') }}
                  <el-checkbox v-model="scope.row.selected" @change="onRowSelect(scope.row)"></el-checkbox>
                </template>
              </el-table-column>
            </div> -->
            <el-table-column
              prop="certTypeName"
              label="资格证书名称"
            ></el-table-column>
            <!-- <el-table-column prop="orderNum" label="排序"></el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
              </template>
            </el-table-column>-->
            <el-table-column label="编码" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.code || "--" }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          {{ optionList.length }}
          <el-form-item label="试验人签字证书配置" v-if="optionList.length">
            <el-checkbox-group v-model="checkList">
              <!-- :disabled="checkList2.includes(item.certTypeId)" -->
              <el-checkbox
                :label="item.certTypeId"
                :disabled="
                  (checkList2.includes(item.certTypeId) ||
                    checkList3.includes(item.certTypeId)) &&
                  formData.type == 2
                "
                :value="item.certTypeId"
                v-for="item in optionList"
                >{{ item.name }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <!-- :disabled="checkList.includes(item.certTypeId)" -->
          <el-form-item label="审核人签字证书配置" v-if="optionList.length">
            <el-checkbox-group v-model="checkList2">
              <el-checkbox
                :label="item.certTypeId"
                :disabled="
                  (checkList.includes(item.certTypeId) ||
                    checkList3.includes(item.certTypeId)) &&
                  formData.type == 2
                "
                v-for="item in optionList"
                >{{ item.name }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <!-- :disabled="checkList.includes(item.certTypeId)" -->
          <el-form-item label="批准人签字证书配置" v-if="optionList.length">
            <el-checkbox-group v-model="checkList3">
              <el-checkbox
                :label="item.certTypeId"
                :disabled="
                  (checkList2.includes(item.certTypeId) ||
                    checkList.includes(item.certTypeId)) &&
                  formData.type == 2
                "
                v-for="item in optionList"
                >{{ item.name }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-col :span="24">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!$route.query.isInfo" type="primary" @click="submitForm">提交</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
          <el-button :disabled="false" type="primary" v-if="formData.isSure == 0 && $route.query.isInfo"
            @click="docBaseSure">确认信息</el-button>
          <el-button :disabled="false" type="primary" v-if="formData.hasAccount == 0 && $route.query.isInfo"
            @click="handleAccount">创建账号</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import { listCertType } from "@/api/system/qualification.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  userDocCertType,
  batchAddUserDocCertType,
  userDocCertTypeSelf,
  queryById,
} from "@/api/finance/personnel/file.js";
export default {
  components: { Treeselect },
  dicts: ["sys_normal_disable"],
  props: [],
  data() {
    return {
      checkList: [],
      checkList2: [],
      checkList3: [],
      formData: { type: "1", certTypeId: undefined, certTypeItems: [] },
      cretList: [],
      cretListOld: [],
      optionList: [],
      rules: {
        certTypeId: [
          { required: true, message: "资格证书不能为空", trigger: "blur" }
        ]
      },
      // 查询参数
      queryParams: {
        certTypeName: undefined,
        status: undefined,
      },
      // 遮罩层
      loading: true,
      // 表格树数据
      deptList: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      arr: [],
      indexArr: [],
      RowArr: [],
    };
  },
  computed: {},
  created() {
    this.getList();
  },
  watch: {
    checkList: {
      handler(e, o) {
        console.log(e, o);
        if (e && e.length == 0) return;
        this.queryFun(e.join(","), o, 6);
      },
    },
    checkList2: {
      handler(e, o) {
        console.log(e, o);
        if (e && e.length == 0) return;
        this.queryFun(e.join(","), o, 9);
      },
    },
  },
  mounted() {
    // this.handleAddCertType();
  },
  methods: {
    newArrFn(arr) {
      return arr.filter((item, index) => {
        return arr.indexOf(item) == index;
      });
    },
    queryFun(e, o, i) {
      console.log(e);
      queryById({ certTypeIds: e }).then((res) => {
        console.log(res);
        let arr = [];
        res.data.forEach((item) => {
          arr.push(item.parentId);
        });
        this.newArrFn(arr);
        console.log(this.newArrFn(arr));
        this.certTypeIds = this.newArrFn(arr).length;
        if (i == 6 && this.certTypeIds == 6) {
          this.checkList = o;
          this.$modal.msgWarning("最多选择5项证书");
        } else if (i == 9 && this.certTypeIds == 9) {
          this.checkList2 = o;
          this.$modal.msgWarning("最多选择8项证书");
        }
      });
    },
    /** 转换资格证书数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.certTypeId,
        label: node.certTypeName,
        children: node.children
      };
    },
    submitForm: function () {
      this.$refs["elForm"].validate(valid => {
        if (valid) {
          console.log(this.formData.certTypeId);
          let certTypeItems = this.cretListOld.filter((e) =>
            this.formData.certTypeId.includes(e.certTypeId)
          );
          console.log(certTypeItems);
          console.log(this.checkList, this.checkList2, this.checkList3);
          this.formData.certTypeItems = certTypeItems.map((e) => {
            if (this.checkList.includes(e.certTypeId)) {
              e = { certTypeId: e.certTypeId, flag: 1, };
            } else if (this.checkList2.includes(e.certTypeId)) {
              e = { certTypeId: e.certTypeId, flag: 2 };
            } else if (this.checkList3.includes(e.certTypeId)) {
              e = { certTypeId: e.certTypeId, flag: 3 };
            } else {
              e = { certTypeId: e.certTypeId };
            }
            return e;
          });
          console.log(this.formData.certTypeItems);
          batchAddUserDocCertType(this.formData).then(response => {
            this.$modal.msgSuccess("设置成功");
          });
        }
      });
    },
    onRowSelect(row, index) {
      console.log(row,index);
      // let nowArr = []
      // nowArr.push(...this.optionList)
      if(this.optionList.length > 0) {
        this.RowArr.push(...this.optionList)
      }
      console.log(this.optionList,this.RowArr,'////----====-----=-=-=-==');

      if (row.selected) {
        this.arr.push(row.certTypeId);
        this.indexArr.push(index);
        this.RowArr.push(row);
      } else {
        this.arr.forEach((itm, inx) => {
          if (itm == row.certTypeId) {
            this.arr.splice(inx, 1);
            this.indexArr.splice(inx, 1);
            this.RowArr.splice(inx, 1);
          }
        });
      }
      // 创建一个临时数组存储索引和值的对应关系
      const tempArr = this.indexArr.map((index, i) => ({
        index,
        value: this.arr[i],
        row: this.RowArr[i],
      }));
      console.log( this.RowArr,' this.RowArr正确');
      console.log(tempArr);

      tempArr.sort((a, b) => a.index - b.index);
      this.arr = tempArr.map((item) => item.value);
      this.indexArr = tempArr.map((item) => item.index);
      this.RowArr = tempArr.map((item) => item.row);
      console.log(this.indexArr,this.RowArr);
      let certTypeIds = [];
      certTypeIds.push(row.certTypeId);
      this.optionList = this.RowArr.filter((i) => {
        let findIndex = this.cretListOld.findIndex(
          (_i) => _i.certTypeId == i.certTypeId
        );
        return findIndex != -1;
      });
      console.log(nowArr);
      // this.optionList.push(...nowArr)
      console.log(this.optionList,this.arr);
      queryById({ certTypeIds: this.arr.join(",") }).then((response) => {
        console.log(this.arr);
        this.optionList.forEach((item, index) => {
          console.log(item);
          this.arr.forEach((lab) => {
            if (item.certTypeId == lab) {
              let name = "";
              // 公路/水运
              if (this.formData.type == 1) {
                response.data.forEach((val) => {
                  if (lab == val.certTypeId) {
                    val.parentCertName =
                      val.parentCertName &&
                      val.parentCertName.slice(
                        0,
                        val.parentCertName.length - 1
                      );
                    name = val.parentCertName.join(",");
                    item.name = name + "(" + item.certTypeName + ")";
                    this.$forceUpdate();
                  }
                });
                // 建设工程
              } else {
                response.data.forEach((val) => {
                  if (lab == val.certTypeId) {
                    val.parentCertName = val.parentCertName.slice(
                      0,
                      val.parentCertName.length - 1
                    );
                    name = val.parentCertName.join(",");
                    item.name = item.certTypeName + "(" + name + ")";
                    this.$forceUpdate();
                  }
                });
              }
            }
          });
        });
      });
      if (row.selected) {
        this.formData.certTypeId.push(row.certTypeId);
      } else {
        this.formData.certTypeId.forEach((item, index) => {
          if ((item = row.certTypeId)) {
            this.formData.certTypeId.splice(index, 1);
          }
        });
      }
      // this.formData.certTypeItems = row
      this.formData.applyScope = JSON.stringify(row);
      // this.formData.scopes.push(row)
      // this.formData.contentList = row
      // console.log(this.formData.contentList, 'undefined');
    },
    traverse(data, checked) {
      // console.log(data.length, 'data');
      data.forEach((row, i) => {
        if (row.certTypeId == checked) {
          this.$set(row, "selected", true);
        }
        if (row.children && row.children.length > 0) {
          // if (this.formData.type == '2') {
          //  this.arr.push(row.certTypeId)
          // checked ? this.arr.push(row.certTypeId) : this.arr.splice(i, 1)

          // }
          this.traverse(row.children, checked);
        }
        if (row.children && row.children.length > 0) {
          // if (this.formData.type == '2') {
          //  this.arr.push(row.certTypeId)
          // checked ? this.arr.push(row.certTypeId) : this.arr.splice(i, 1)

          // }
          this.traverse(row.children, checked);
        }
      })
    },
    /** 查询资格证书列表 */
    getList() {
      this.loading = true;
      this.queryParams.type = this.formData.type;
      listCertType(this.queryParams).then(response => {
        this.cretListOld = response.data;
        this.deptList = this.handleTree(response.data, "certTypeId");
        // console.log(this.deptList);
        this.loading = false;
        this.handleAddCertType(this.formData.type)
      });
    },
    /** 查询资格证书列表 */
    getList() {
      this.loading = true;
      this.queryParams.type = this.formData.type;
      listCertType(this.queryParams).then((response) => {
        this.cretListOld = response.data;
        this.deptList = this.handleTree(response.data, "certTypeId");
        // console.log(this.deptList);
        this.loading = false;
        this.handleAddCertType(this.formData.type);
      });
    },
    // getCretList(e) {
    //   listCertType({ type: this.formData.type }).then((response) => {
    //     this.cretList = this.handleTree(response.data, "certTypeId");
    //     this.cretListOld = response.data;
    //     if (e) {
    //       userDocCertTypeSelf({
    //         userDocBaseId: this.formData.userDocBaseId,
    //         type: this.formData.type,
    //       }).then((res) => {
    //         this.formData.certTypeId = res.data.map((i) => i.certTypeId);
    //         this.optionList = res.data;
    //         this.checkList = res.data
    //           .filter((e) => e.flag == 1)
    //           .map((e) => e.certTypeId);
    //         this.checkList2 = res.data
    //           .filter((e) => e.flag == 2)
    //           .map((e) => e.certTypeId);
    //         console.log(this.checkList2);
    //       });

    //       console.log(this.checkList);
    //     }
    //   });
    // },
    change(e) {
      this.optionList = this.cretListOld.filter((i) =>
        e.includes(i.certTypeId)
      );
      console.log(this.optionList);
    },
    changeTab() {
      this.formData.certTypeId = [];
      this.arr = [];
      this.indexArr = [];
      this.RowArr = [];
      // this.getCretList(true);
      this.getList();
    },
    resetForm() {
      this.$tab.closeOpenPage();
    },
    userDocCertTypeSelf() {
      this.formData.userDocBaseId = this.$route.query.id.toString();
    },
    handleAddCertType(row) {
      // this.getCretList();
      this.formData.userDocBaseId = this.$route.query.id.toString();
      userDocCertTypeSelf({
        userDocBaseId: this.formData.userDocBaseId,
        type: this.formData.type,
      }).then((res) => {
        this.formData.certTypeId = res.data.map((i) => i.certTypeId);
        this.checkList = res.data
          .filter((e) => e.flag == 1)
          .map((e) => e.certTypeId);
        console.log(this.checkList);
        this.checkList2 = res.data
          .filter((e) => e.flag == 2)
          .map((e) => e.certTypeId);
        this.checkList3 = res.data
          .filter((e) => e.flag == 3)
          .map((e) => e.certTypeId);
        this.optionList = this.cretListOld.filter((i) =>
          this.formData.certTypeId.includes(i.certTypeId)
        );
        this.optionList.forEach((item) => {
          this.arr.push(item.certTypeId);
        });
        if (this.arr.length > 0) {
          queryById({ certTypeIds: this.arr.join(",") }).then((response) => {
            this.optionList.forEach((item, index) => {
              this.arr.forEach((lab) => {
                if (item.certTypeId == lab) {
                  let name = "";
                  if (this.formData.type == 1) {
                    response.data.forEach((val) => {
                      if (lab == val.certTypeId) {
                        val.parentCertName =
                          val.parentCertName &&
                          val.parentCertName.slice(
                            0,
                            val.parentCertName.length - 1
                          );
                        if (!val.parentCertName) return;
                        name =
                          val.parentCertName && val.parentCertName.join(",");
                        item.name = name + "(" + item.certTypeName + ")";
                        this.$forceUpdate();
                      }
                    });
                  } else {
                    response.data.forEach((val) => {
                      if (lab == val.certTypeId) {
                        val.parentCertName = val.parentCertName.slice(
                          0,
                          val.parentCertName.length - 1
                        );
                        console.log(val.parentCertName);
                        name = val.parentCertName.join(",");
                        item.name = item.certTypeName + "(" + name + ")";
                        this.$forceUpdate();
                      }
                    });
                  }
                }
              });
            });
          });
        }

        console.log(
          this.cretListOld,
          this.optionList,
          this.formData.certTypeId
        );

        this.cretListOld.forEach((item, index) => {
          this.formData.certTypeId.forEach((lab, val) => {
            if (item.certTypeId == lab) {
              // item.selected = true
              this.$set(item, "selected", true);
              console.log(item);
              if (item.children && item.children.length > 0) {
                this.traverse(item.children, lab);
              }
            } else {
              if (item.children && item.children.length > 0) {
                this.traverse(item.children, lab);
              }
            }
          });
        });
      });
      // userDocCertType({
      //   userDocBaseId: this.formData.userDocBaseId,
      //   type: this.formData.type,
      // }).then((res) => {
      //   this.formData.certTypeId = res.data
      //     .filter((e) => e.selectFlag)
      //     .map((i) => i.certTypeId);
      // });
    }
  }
};
</script>
